package com.jims.master.modules.drug.service;

import com.jims.master.common.data.StringData;
import com.jims.master.common.persistence.Page;
import com.jims.master.common.service.CrudService;
import com.jims.master.common.utils.PrintPdfUtils;
import com.jims.master.common.web.impl.BaseDto;
import com.jims.master.modules.drug.dao.*;
import com.jims.master.modules.drug.entity.*;
import com.jims.master.modules.sys.dao.CompanyDao;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 药品出库处理Service
 * @author fengyg
 * @version 2017-03-17
 */
@Service
@Transactional(readOnly = true)
public class DrugExportService extends CrudService<DrugExportDetailDao,DrugExportDetail>{
    @Autowired
    private DrugInfoService drugInfoService;
    @Autowired
    private DrugStockService stockService;
    @Autowired
    private DrugStorageDeptService drugStorageDeptService;
    @Autowired
    private DrugExportMasterDao exportMasterDao;
    @Autowired
    private DrugStorageDeptDao drugStorageDeptDao;
    @Autowired
    private DrugExportMasterDao drugExportMasterDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private DrugExportDetailDao DrugExportDetailDao;
    @Autowired
    private DrugStockDao drugStockDao;
    @Autowired
    private DrugInfoDao drugInfoDao;


    public Page<DrugExportDetail> findPage(Page<DrugExportDetail> page, DrugExportDetail drugExportDetail) {
        return super.findPage(page, drugExportDetail);
    }

    /**
     * 出库单据查询
     * @param page 分页对象
     * @param drugExportDetail
     * @return
     */
    public Page<DrugExportDetail> findDetailList(Page<DrugExportDetail> page, DrugExportDetail drugExportDetail) {
        drugExportDetail.updateOrgId();
        drugExportDetail.setPage(page);
        page.setList(dao.findDetailList(drugExportDetail));
        return page;
    }
    /**
     * 出库记录查询
     * @param
     * @param drugExportMaster
     * @return
     */
    public Page<DrugExportMaster> findExportList(Page<DrugExportMaster> page, DrugExportMaster drugExportMaster) {
        drugExportMaster.updateOrgId();
        drugExportMaster.setPage(page);
        page.setList(drugExportMasterDao.findExportList(drugExportMaster));
        return page;
    }

    /**
     * 出库待入库记录查询
     * @param
     * @param drugExportMaster
     * @return
     */
    public Page<DrugExportMaster> batchImport(Page<DrugExportMaster> page, DrugExportMaster drugExportMaster) {
        drugExportMaster.updateOrgId();
        drugExportMaster.setPage(page);
        page.setList(drugExportMasterDao.batchImport(drugExportMaster));
        return page;
    }

    /**
     * 出库详情查询
     * @param drugExportDetail
     * @return
     */
    public List<DrugExportDetail> findBymasterId(DrugExportDetail drugExportDetail) {
        drugExportDetail.updateOrgId();
        return dao.findBymasterId(drugExportDetail);
    }

    /**
     * 药品出库选择有库存有价格的药品自动补全
     * @param drugInfo
     * @param orgId
     * @return
     * @author fengyg
     * @date 2017-03-17
     */
    public List<DrugExportDetail> autoExportStock(DrugInfo drugInfo, String orgId, String q, String limit) {
        List<DrugExportDetail> drugExportDetails = dao.autoExportStock(drugInfo, orgId, q, limit, UserUtils.getUser().getOrgDept().getId());
        return drugExportDetails;
    }


    /**
     * 药品出库处理
     * @param detailList
     * @return
     * @author fengyg
     */
    @Transactional(readOnly = false)
    public StringData saveExportList(List<DrugExportDetail> detailList){
        int num = 0;
        StringData data = new StringData();
        Double money = 0.00;   //应付款
        if(null != detailList && detailList.size() > 0){
            //出库主表
            DrugExportMaster master = detailList.get(0).getDrugExportMaster();
            master.preInsert();
            master.updateOrgId();
            master.setStorageId(UserUtils.getUser().getOrgDept().getId());  //获取当前部门对应的id
            master.setDocumentNo(this.createDocumentNo(master));  //修改出库单号的生成
            master.setStorageId(UserUtils.getUser().getOrgDept().getId());  //当前库房
            master.setExportDate(new Date());    //出库日期
            List<DrugStorageDept> storageList = drugStorageDeptDao.getByName(detailList.get(0).getDrugExportMaster().getReceiver(), UserUtils.getOrgId());
            if(null != storageList && storageList.size() > 0){
                for (DrugStorageDept storage : storageList) {
                    if(detailList.get(0).getDrugExportMaster().getReceiver().equals(storage.getStorageName())){
                        master.setReceiver(storage.getStorageCode());  //收货方
                        break;
                    }
                }
            }
            master.setExportClass(detailList.get(0).getDrugExportMaster().getExportClass());  //出库类别
            master.updateOrgId();
            //对应的入库者
            //对应的入库日期
            //对应的入库主表ID
            String printMasterId=master.getId();
            for (int i = 0; i < detailList.size(); i++) {
                DrugExportDetail detail = new DrugExportDetail();
                //获取库存表和info表的数据，比较包装规格，判断实际上发了多少
                DrugStock drugStock =new DrugStock();
                drugStock=drugStockDao.get(detailList.get(i).getId());
                DrugInfo drugInfo =new DrugInfo();
                drugInfo=drugInfoDao.get(detailList.get(i).getInfoId());
                detail = detailList.get(i);
                detail.preInsert();
                detail.setMasterId(master.getId());
                detail.setItemNo((i + 1) + "");
                detail.setInfoId(detail.getDrugStock().getInfoId());
                detail.setPurchasePrice(detail.getDrugPrice().getRetailPrice());
                money += detail.getQuantity() * detail.getDrugPrice().getRetailPrice(); //计算应付款
                StringData stringData= new StringData();
                Double inventory =0.0;
                if(drugInfo.getPackageSpec() .equals(drugStock.getPackageSpec())){
                    inventory=drugStock.getQuantity()-detail.getQuantity()*drugInfo.getPackageNum();
                    detail.setInventory(inventory);
                    detail.setQuantity(detail.getQuantity()*drugInfo.getPackageNum());
                    drugStock.setQuantity(inventory);
                }else{
                    inventory=drugStock.getQuantity()-detail.getQuantity();
                    detail.setInventory(inventory);
                    detail.setQuantity(detail.getQuantity());
                    drugStock.setQuantity(inventory);
                }
                if(inventory < 0){
                    stringData.setCode("error");
                    stringData.setData("该药品当前批次库存数量不够,无法出库!");
                    return stringData;
                }

                detail.updateOrgId();
                detail.setImportMasterId(detail.getDrugStock().getImportMasterId());
                detail.setPackageUnits(DictUtils.getDictValue(detail.getPackageUnits(),"SPEC_UNIT",""));
                detail.setMinUnits(DictUtils.getDictValue(detail.getMinUnits(), "SPEC_UNIT",""));
                //保存出库明细表
                num += dao.insert(detail);
                //修改库存量
                drugStock.preUpdate();
                num +=drugStockDao.update(drugStock);
            }
            master.setAccountReceivable(money); //出库主表设置应付款
            //保存出库主表
            num += exportMasterDao.insert(master);
            if(num > 0){
                data.setCode("success");
                data.setData(printMasterId);
            }else{
                data.setCode("error");
                data.setData("药品出库失败!");
            }
        }else{
            data.setCode("error");
            data.setData("没有要保存的数据!");
        }
        return data;
    }

    /**
     * 根据供货方ID(storageId)查询需要批量入库的数据
     * @param storageId 供货方ID
     * @return
     * @author fengyg
     */
    @Transactional
    public List<DrugStock> getBatchExportList(String storageId){
        List<DrugStock> list = dao.getBatchImportList(storageId, UserUtils.getUser().getOrgDept().getId(), UserUtils.getOrgId());
        if(null != list && list.size() > 0){
            for (DrugStock batchExport : list) {
                batchExport.getDrugExportDetail().setPackageUnits(DictUtils.getDictLabel(batchExport.getDrugExportDetail().getPackageUnits(),"SPEC_UNIT",""));
                batchExport.getDrugExportDetail().setMinUnits(DictUtils.getDictLabel(batchExport.getDrugExportDetail().getMinUnits(),"SPEC_UNIT",""));
            }
        }else{
            return new ArrayList<DrugStock>();
        }
        return list;
    }




    /*
    * 根据传来的drugExportMaster数据生成出库单据号
    * @ZhuQ
    * */
    public String createDocumentNo (DrugExportMaster drugExportMaster){

        //根据库房获取入库单前缀
        DrugStorageDept drugStorageDept=drugStorageDeptDao.getByStorageCode(drugExportMaster.getStorageId());
        String documentNo=drugStorageDept.getExportNoPrefix();
        //获取当前日期
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
        documentNo=documentNo+ sdf.format(d);
        drugExportMaster.setDocumentNo(documentNo);
        //序号
        int i = drugExportMasterDao.findDocumentNo(drugExportMaster);
        String num = String.valueOf(i);
        String str ="0000";
        str=str.substring(0, 4-num.length())+num;
        documentNo=documentNo+str;
        return documentNo;
    }

    //根据传来的drugStock数据组装成drugExportDetail数据
    public DrugExportDetail createData(DrugStock drugStock,int itemNo,String masterId){
        DrugExportDetail drugExportDetail=new DrugExportDetail();
        drugExportDetail.setMasterId(masterId);		// 主表Id
        drugExportDetail.setItemNo(String.valueOf(itemNo+1));	// 序号
        drugExportDetail.setDrugCode(drugStock.getDrugCode());		// 药品编码
        drugExportDetail.setInfoId(drugStock.getInfoId());		// drugInfoId
        drugExportDetail.setPackageNum(drugStock.getPackageNum());		// 包装数量
        drugExportDetail.setPackageSpec(drugStock.getPackageSpec());		// 包装规格
        drugExportDetail.setPackageUnits(drugStock.getPackageUnits());		// 包装单位
        drugExportDetail.setMinSpec(drugStock.getMinSpec());		// 最小规格
        drugExportDetail.setMinUnits(drugStock.getMinUnits());		// 最小单位
        drugExportDetail.setPurchasePrice(drugStock.getPurchasePrice());		// 进货价
//        drugExportDetail.setDiscount(drugStock.getDiscount());		// 折扣
        drugExportDetail.setBatchNo(drugStock.getBatchNo());		// 批号
        drugExportDetail.setExpireDate(drugStock.getExpireDate());		// 有效期
        drugExportDetail.updateOrgId();		// 机构ID
        drugExportDetail.preInsert();
        return drugExportDetail;
    }

    /**
     * 药品出库单据打印
     * @param drugExportDetail
     * @return
     */
    public String drugExportDetailsPrint(DrugExportDetail drugExportDetail){
        User user = UserUtils.getUser();
        String deptId=null!=user.getOrgDept()?user.getOrgDept().getId():"";
        drugExportDetail.setStorageId(deptId);
        List<BaseDto> list= DrugExportDetailDao.findDetailListPrint(drugExportDetail);
        DrugExportDetail entityForNum=dao.findNumByName(drugExportDetail);
        int num=entityForNum.getNum();
        Map map = new HashMap();
        String hospital = UserUtils.getUser().getCompany().getOrgName();
        String title="药品出库凭证";
        Double tradePriceTotal=0.0;
        Double retailPriceTotal=0.0;
        if(list.size()>0){
            BaseDto detail=list.get(0);
            DrugStorageDept drugStorageDept=drugStorageDeptService.get(detail.getAsString("receiver"));
            if(null!=drugStorageDept){
                map.put("receiver",drugStorageDept.getStorageName());//收货库房
            }
            else {
                map.put("receiver","");
            }
            map.put("exportClass",DictUtils.getDictLabel(detail.getAsString("exportClass"), "DRUG_STOTARG_TYPE", ""));//出库类别
            map.put("documentNo",detail.getAsString("documentNo"));//出库单号
            map.put("exportDate",detail.getAsString("exportDate"));//出库日期
            map.put("storageName",detail.getAsString("storageName"));//库房
//            if("1".equals(drugExportDetail.getRemarks())){
//                map.put("receiver","");
//                map.put("storageName","");
//            }
            int i=1;
            for(BaseDto detail1:list){
                DrugInfo drugInfo=drugInfoService.get(detail1.getAsString("infoId"));
                if(drugInfo!=null&&drugInfo.getPackageSpec().equals(detail1.getAsString("packageSpec"))){
                    detail1.put("quantity",Integer.parseInt(detail1.getAsString("quantity"))/Integer.parseInt(detail1.getAsString("packageNum")));
                }
                detail1.put("minUnits",DictUtils.getDictLabel(detail.getAsString("minUnits"), "SPEC_UNIT", ""));
                detail1.put("index",Integer.toString(i++));
                detail1.put("expireDate",detail1.getAsString("expireDate"));
                Double totalTrade=Double.parseDouble(detail1.getAsString("tradePrice"))*Double.parseDouble(detail1.getAsString("quantity"));
                Double totalRetail=Double.parseDouble(detail1.getAsString("retailPrice"))*Double.parseDouble(detail1.getAsString("quantity"));
                detail1.put("totalTrade",String.format("%.2f", totalTrade));
                detail1.put("totalRetail",String.format("%.2f",totalRetail));
                tradePriceTotal+=totalTrade;
                retailPriceTotal+=totalRetail;
            }
        }
        map.put("hospital", hospital);
        map.put("title",title);
        map.put("lists",list);
        map.put("num",num);//品种数量
        map.put("tradePriceTotal",String.format("%.2f", tradePriceTotal));
        map.put("retailPriceTotal",String.format("%.2f", retailPriceTotal));
        String printPath = PrintPdfUtils.previewPdf(user.getId(), "his/drug/drugExportDetailsPrint.jasper", map, list, "drugExportDetailsPrint");
        return  printPath;
    }

    /**
     * 消耗品出库数据统计
     * @param  exportDate,orgId
     * @return
     * @author ZhuQ
     */
    public List<BaseDto> drugExportCount(String exportDate,String orgId ){
        return drugExportMasterDao.drugExportCount(exportDate,orgId);
    }
}
